package com.lizhi.parse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.lizhi.model.ContentModel;
import com.lizhi.model.model2.ChapterModel;
import com.lizhi.util.Util;

public class ParseChapter extends Thread {
	private String host = "http://www.sbkk8.cn";

	ChapterModel mChapterModel;
	String mHref;
	String mNext;

	public ParseChapter(String href) {
		mHref = href;
	}

	public ParseChapter(ChapterModel chapterModel, String href) {
		mChapterModel = chapterModel;
		mHref = href;
	}

	public ParseChapter(ChapterModel chapterModel, String href, String next) {
		mChapterModel = chapterModel;
		mHref = href;
		mNext = next;
	}

	@Override
	public void run() {
		while (true) {

			try {
				System.out.println(mHref);

				Document document = Util.getDocument(host+mHref);
				Elements elements = document.getElementsByClass("f_article").get(0).getElementsByTag("p");
				StringBuilder builder = new StringBuilder();
				if (elements.size() == 0) {
					builder.append(document.getElementsByClass("f_article").get(0).text());
				} else {
					for (Element element : elements) {
						builder.append(element.text());
						builder.append("\n");
					}
				}
				ContentModel contentModel = new ContentModel();
				contentModel.bid = mChapterModel.bid;
				contentModel.content = builder.toString();
				contentModel.content=contentModel.content.replaceAll("<br/>", "\n");
				contentModel.id = mChapterModel.id;
				contentModel.next = mNext;
				contentModel.title = mChapterModel.name;
				System.out.println("upload chapter:" + contentModel.title);
//				System.out.println(contentModel.content);
				Util.uploadPut(Util.getBookURL()+"content/books" + mChapterModel.url, JSON.toJSONString(contentModel));
				break;
			} catch (Exception e) {
				Util.saveFile(mChapterModel.name, mHref);
				e.printStackTrace();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}

		}
	}

	public static void main(String[] args) {
		new ParseChapter("/lizhishu/kaozijiquchenggong/297324.html").start();
	}

}
